package com.hzsai.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * hzsai
 * 2019/8/20 15:57
 * usage:
 */
@Configuration
@MapperScan(basePackages = {"com.hzsai.mappersa"}, sqlSessionFactoryRef = "sqlSessionFactory1")
public class MyBatisDSConfigA {

    @Bean(name = "sqlSessionFactory1")
    @Primary
    public SqlSessionFactory sqlSessionFactory1(@Qualifier(value = "springbootDS") DataSource ds1) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        // debug info
//        System.out.println("Setting SqlSessionFactory, ds1: " + ds1.toString());
        bean.setDataSource(ds1);
        return bean.getObject();
    }

    @Bean(name = "managerDS1")
    @Primary
    public DataSourceTransactionManager managerDS1(@Qualifier(value = "springbootDS") DataSource ds1) {
        return new DataSourceTransactionManager(ds1);
    }

    @Bean(name = "sqlSessionTemplate1")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate1(
            @Qualifier("sqlSessionFactory1") SqlSessionFactory sqlSessionFactory
    ) throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }
}
